package com.deductive.common.config.mybatis;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import java.sql.*;

public class JsonbTypeHandler extends BaseTypeHandler<JsonNode> {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType) throws SQLException {
        try {
            PGobject jsonObject = new PGobject();
            jsonObject.setType("jsonb");
            jsonObject.setValue(parameter == null ? null : OBJECT_MAPPER.writeValueAsString(parameter));
            ps.setObject(i, jsonObject);
        } catch (Exception e) {
            throw new SQLException("Failed to set jsonb parameter", e);
        }
    }

    @Override
    public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object obj = rs.getObject(columnName);
        return parse(obj);
    }

    @Override
    public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object obj = rs.getObject(columnIndex);
        return parse(obj);
    }

    @Override
    public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object obj = cs.getObject(columnIndex);
        return parse(obj);
    }

    private JsonNode parse(Object obj) throws SQLException {
        if (obj == null) return null;
        try {
            if (obj instanceof PGobject) {
                String value = ((PGobject) obj).getValue();
                return value == null ? null : OBJECT_MAPPER.readTree(value);
            }
            if (obj instanceof String) {
                return OBJECT_MAPPER.readTree((String) obj);
            }
            return OBJECT_MAPPER.readTree(String.valueOf(obj));
        } catch (Exception e) {
            throw new SQLException("Failed to parse jsonb", e);
        }
    }
}


